// 使用IIFE模式，避免ES6模块问题
(function () {
    'use strict';

    // 动态加载xpath配置
    let xpathConfig = null;

    // 初始化函数
    async function initXpathConfig() {
        if (xpathConfig) return xpathConfig;

        try {
            // 使用chrome.runtime.getURL正确访问扩展资源
            const configUrl = chrome.runtime.getURL('config/xpath.json');
            console.log('尝试加载配置文件:', configUrl);

            const response = await fetch(configUrl);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            xpathConfig = await response.json();
            console.log('xpath配置加载成功:', xpathConfig);
            return xpathConfig;
        } catch (error) {
            console.log('加载xpath配置失败:', error);
            console.log('尝试使用备用配置...');

            // 备用配置
            xpathConfig = {
                "person": {
                    "input": {
                        "xpath": "//div[@role='banner']//input",
                        "message": "页面搜索框"
                    },
                    "searchResult": {
                        "xpath": "//div[@role='banner']//ul/li/a",
                        "message": "页面搜索结果"
                    },
                    "addFriend": {
                        "xpath": "//div[@role='main']//div[contains(@class, 'x1iyjqo2 x2lwn1j')]//div[@role='button']",
                        "message": "页面加好友按钮"
                    }
                },
                "chat": {
                    "content": {
                        "xpath": "//div[contains(@class, 'xixxii4 x1vjfegm')]//div[@data-visualcompletion='ignore']",
                        "message": "聊天区域"
                    },
                    "item": {
                        "xpath": "div[dir='auto']",
                        "message": "聊天内容"
                    }
                }
            };
            console.log('使用备用配置');
            return xpathConfig;
        }
    }

    // 暴露到全局作用域
    window.getElementNodeValue = async function (str, doc = window.document) {
        // 参数验证
        if (typeof str === 'string') {
            if (!str || typeof str !== 'string') {
                console.log('getElementNodeValue: 参数必须是有效的字符串');
                return null;
            }

            // 确保配置已加载
            const xpath = await initXpathConfig();
            if (!xpath) return null;

            let current = xpath;
            const list = str.split('.');

            // 逐层遍历对象属性
            for (let i = 0; i < list.length; i++) {
                const key = list[i];

                // 检查当前层级是否存在
                if (!current || typeof current !== 'object' || !(key in current)) {
                    console.log(`getElementNodeValue: 路径 "${str}" 在 "${key}" 处无效`);
                    return null;
                }

                current = current[key];
            }

            let classpath = current.xpath;

            // 遍历所有路径，查询匹配的元素
            const element = doc.evaluate(classpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            if (!element.singleNodeValue) {
                console.log(`getElementNodeValue: 路径 "${str}" 无效`);
                return null;
            }
            return element.singleNodeValue;
        } else {
            for (let i = 0; i < str.length; i++) {
                const element = await getElementNodeValue(str[i], doc);
                console.log(element)
                let elementList = []
                if (element) {
                    elementList.push(element);
                }
            }
            return elementList[0];
        }
    };

    window.getElement = async function (str, doc = window.document) {
        // 参数验证
        if (!str || typeof str !== 'string') {
            console.log('getElement: 参数必须是有效的字符串');
            return null;
        }

        // 确保配置已加载
        const xpath = await initXpathConfig();
        if (!xpath) return null;

        let current = xpath;
        const list = str.split('.');

        for (let i = 0; i < list.length; i++) {
            const key = list[i];
            if (!current || typeof current !== 'object' || !(key in current)) {
                console.log(`getElement: 参数必须是有效的字符串`);
                return null;
            }
            current = current[key];
        }

        let classpath = current.xpath;

        // 遍历所有路径，查询匹配的元素
        const element = doc.evaluate(classpath, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        if (!element) {
            console.log(`getElement: 路径 "${str}" 无效`);
            return null;
        }
        return element;
    };

    window.getXpath = async function (str) {
        // 参数验证
        if (!str || typeof str !== 'string') {
            console.log('getXpath: 参数必须是有效的字符串');
            return null;
        }

        // 确保配置已加载
        const xpath = await initXpathConfig();
        if (!xpath) return null;

        let current = xpath;
        const list = str.split('.');

        for (let i = 0; i < list.length; i++) {
            const key = list[i];
            if (!current || typeof current !== 'object' || !(key in current)) {
                console.log(`getXpath: 路径 "${str}" 在 "${key}" 处无效`);
                return null;
            }
            current = current[key];
        }

        let classpath = current.xpath;
        return classpath;
    };

    console.log('getElement 模块已加载到全局作用域');
})();
